package com.geek.pokermanager.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.geek.pokermanager.model.User;
import com.geek.pokermanager.util.ConfigTool;
import com.geek.pokermanager.util.FileTools;
import com.geek.pokermanager.util.JacksonUtil;

@Controller
@RequestMapping(value="base")
public class BaseController {

	@Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpServletResponse response;

    @Resource
    protected HttpSession session;
	
	protected BaseResult returnResult=null;
	
	protected Date nowDate=new Date();
	
	protected static Log log= LogFactory.getLog(BaseController.class);
	
	@SuppressWarnings("rawtypes")
	@ModelAttribute("returnResult")
	public String setReturnResult(HttpServletRequest request) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		returnResult=new BaseResult();
		return null;
	}
	
    @ExceptionHandler
    @ResponseBody
    public String exception(HttpServletRequest request, Exception e) {  
    	returnResult=new BaseResult();
    	if(e instanceof BadSqlGrammarException){    		
    		log.error("SQL错误："+((BadSqlGrammarException)e).getSql()+
    				"\n Cause:"+((BadSqlGrammarException)e).getCause());
    	}
    	returnResult.setError(true);
    	returnResult.setMsg(e.getMessage());
		return resultVal();
    }  
    @RequestMapping("/difined")
    public String difined(HttpServletRequest request,HttpServletResponse response){
    	System.err.println("difined");
    	writeJson(response);
    	return null;
    }
    @RequestMapping(value="/index")
    public String index(Model model) throws IOException{
    	model.addAttribute("Context",basePath());
    	String pokerFolderPath=request.getSession().getServletContext().getRealPath("image/pokerFace");
    	model.addAllAttributes(FileTools.getFile(pokerFolderPath));
    	return "index";
    }
    /**
	 * 登录
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="loginData",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String login(String userName,String pwd,HttpServletRequest request,HttpServletResponse response){
		userName=request.getParameter("userName");
		pwd=request.getParameter("pwd");
		User user=new User(userName,pwd);
		if(StringUtils.isNotBlank(userName) 
				&& StringUtils.isNotBlank(pwd)
				&& pwd.equals(ConfigTool.getString("Game.accountPwd")) 
				&& userName.equals(ConfigTool.getString("Game.accountName"))){
			session.setAttribute(request.getLocalAddr(), user);
			returnResult.setMsg("登录成功！");
		}else{
			returnResult.setError(true);
			returnResult.setMsg("登录失败！");
		}
		return resultVal();
	}
	@RequestMapping(value="login")
	public ModelAndView loginPage(Model model){
		model.addAttribute("Context",basePath());
		model.addAttribute("ContextPath",request.getContextPath());
		return new ModelAndView("login");
	}
    private void writeJson(HttpServletResponse response){
    	 PrintWriter out = null;
         try {
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application/json; charset=utf-8");
             out = response.getWriter();
             out.write(resultVal()==null?"{}":resultVal());
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (out != null) {
                 out.close();
             }
         }
    }
    
	public BaseResult getReturnResult() {
		return returnResult;
	}

	public void setReturnResult(BaseResult returnResult) {
		this.returnResult = returnResult;
	}

	
	public String resultVal(){
		return JacksonUtil.getJsonFromObject(this.returnResult);
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}
	/**
	 * 获取当前路径
	 * @return
	 */
	protected String basePath(){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
	}
}
